package com.googlecode.perfectable.visuable.message;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;

import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonTypeName;

import com.googlecode.perfectable.prosperable.message.ClientMessage;
import com.googlecode.perfectable.prosperable.message.ServerMessage;
import com.googlecode.perfectable.visuable.visual.ValueHoldingVisual;

@JsonTypeName("value-change")
public class ValueChangeMessage implements ClientMessage, ServerMessage { // MARK server and client message?
	private static final long serialVersionUID = 2524940205203742175L;

	private final String visualIdentifier;
	private final String newValue;

	private ValueChangeMessage(String visualIdentifier, String newValue) {
		this.visualIdentifier = visualIdentifier;
		this.newValue = newValue;
	}

	public boolean isDirectedAt(ValueHoldingVisual context) {
		return context.identifier().equals(this.visualIdentifier);
	}

	public void perform(ValueHoldingVisual visual) {
		checkState(this.isDirectedAt(visual));
		visual.setValue(this.newValue);
	}

	public static ValueChangeMessage create(ValueHoldingVisual visual, String newValue) {
		return new ValueChangeMessage(visual.identifier(), newValue);
	}

	@JsonCreator
	public static ValueChangeMessage construct(
			@JsonProperty("visual-identifier") String visualIdentifier,
			@JsonProperty("value") String newValue) {
		return new ValueChangeMessage(checkNotNull(visualIdentifier), checkNotNull(newValue));
	}

	@JsonProperty("visual-identifier")
	private final String getSource() {
		return this.visualIdentifier;
	}

	@JsonProperty("value")
	private final String getValue() {
		return this.newValue;
	}

}
